package com.haoran.dwz.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.haoran.dwz.model.Server;
import com.orbitz.consul.Consul;
import com.orbitz.consul.model.health.ServiceHealth;

@Component
public class ServiceDiscovery {
	
	@Autowired
	private Consul consul;

	public List<Server> getServerList(String serviceName) {

		List<Server> list = new ArrayList<>();
		List<ServiceHealth> availableServers = consul.healthClient().getHealthyServiceInstances(serviceName)
				.getResponse();

		for (ServiceHealth serviceHealth : availableServers) {
			list.add(new Server(serviceHealth.getNode().getAddress(), serviceHealth.getService().getPort()));
		}

		return list;
	}
}
